//
//  LiveRoomViewUIControllerViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/2/26.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "LiveRoomViewUIControllerViewController.h"
#import "UserPageInfoModel.h"
#import "GiftView.h"
#import "GiftLogic.h"
#import "VMsgMessage.h"
#import "LiveGiftShowCustom.h"

#define BuckleSecond 60


@interface LiveRoomViewUIControllerViewController ()<GiftViewDelegate,LiveGiftShowCustomDelegate>
@property(nonatomic, strong)  UserPageInfoModel *usermodel;
@property(nonatomic, strong) NSTimer *timer;//扣费计时器
@property(nonatomic, strong) UILabel *roomTip;//扣费提示
@property(nonatomic, assign) int is_need_coin;
@property(nonatomic, strong) NSString *video_deduction;
//礼物
@property(nonatomic, strong) GiftView *giftview;
@property(nonatomic, strong)  GiftLogic *giftLogic;
@property(nonatomic, strong) NSArray *giftList;

@property (nonatomic ,weak) LiveGiftShowCustom * customGiftShow;

//@property(nonatomic, strong) UIButton *MaskButton;
@end

@implementation LiveRoomViewUIControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self getData];
    [self getInitData];
    [self startService];//启动服务
    self.view.backgroundColor = KBlackColor;
}

-(void)createUI
{
    _topBg = [[UIView alloc] init];
    _topBg.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.4];
    [self.view addSubview:_topBg];
    
    //头像
    _headerImage = [[UIImageView alloc] init];
    _headerImage.contentMode = UIViewContentModeScaleAspectFill;
    
    _headerImage.qmui_needsDifferentDebugColor = YES;
    _headerImage.qmui_shouldShowDebugColor = YES;
    //昵称
    _nickname = [[UILabel alloc] init];
    _nickname.textColor = [UIColor whiteColor];
    _nickname.font = DEFAULT_FONT(14);
    
    [_topBg addSubview:_headerImage];
    [_topBg addSubview:_nickname];
    
    //底部按钮
    _refuseButton = [[UIButton alloc] init];
    [_refuseButton setImage:IMAGE_NAMED(@"home_alert_refuse") forState:UIControlStateNormal];
    [_refuseButton addTarget:self action:@selector(handleRefuseButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    _microphoneButton = [[UIButton alloc] init];
    [_microphoneButton setImage:[UIImage imageNamed:@"btn_mute"] forState:UIControlStateNormal];
    [_microphoneButton setImage:[UIImage imageNamed:@"btn_mute_cancel"] forState:UIControlStateSelected];
    [_microphoneButton addTarget:self action:@selector(handlemicrophonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    _cameraButton = [[UIButton alloc] init];
    [_cameraButton setImage:[UIImage imageNamed:@"btn_overturn"] forState:UIControlStateNormal];
    [_cameraButton setImage:[UIImage imageNamed:@"btn_overturn"] forState:UIControlStateSelected];
    [_cameraButton addTarget:self action:@selector(handlcameraEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _giftButton = [[UIButton alloc] init];
    [_giftButton setImage:[UIImage imageNamed:@"callgift"] forState:UIControlStateNormal];
    [_giftButton setImage:[UIImage imageNamed:@"callgift"] forState:UIControlStateSelected];
    [_giftButton addTarget:self action:@selector(showGiftView) forControlEvents:UIControlEventTouchUpInside];
    if (!(IsCurrentUserMale)) {
        _giftButton.hidden = YES;
    }
    
    //    _MaskButton = [[UIButton alloc] init];
    //    [self.view addSubview:_MaskButton];
    //    _MaskButton.hidden = YES;
    
    [self.view addSubview:_topBg];
    [self.view addSubview:_refuseButton];
    [self.view addSubview:_microphoneButton];
    [self.view addSubview:_cameraButton];
    //    [self.view addSubview:_MaskButton];
    [self.view addSubview:_giftButton];
    
    
    _redStopwatch = [[MZTimerLabel alloc] init];
    _redStopwatch.frame = CGRectMake(SCREEN_WIDTH - 100,40,100,20);
    _redStopwatch.timeFormat = @"HH:mm:ss";
    _redStopwatch.timeLabel.font = [UIFont systemFontOfSize:20.0f];
    _redStopwatch.timeLabel.textColor = MainColor;
    [self.view addSubview:_redStopwatch];
    
    _roomTip = [[UILabel alloc] init];
    
    _roomTip.text = [NSString stringWithFormat:ASLocalizedString(@"每分钟通话扣除%@%@"),KGlobalVariable.appmodel.video_deduction,KCOIN_NAME];
    _roomTip.frame = CGRectMake(SCREEN_WIDTH - 200,100,200,20);
    _roomTip.font = DEFAULT_FONT(12);
    _roomTip.textColor = MainColor;
    _roomTip.textAlignment = NSTextAlignmentRight;
    _redStopwatch.timeLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.view addSubview:_roomTip];
    [_redStopwatch start];//计时器
    
    
    [self setLayot];
}

-(void)clickBackView
{
    [super clickBackView];
    _giftview.hidden = YES;
}

- (void)showGiftView {
    //显示gift
    _giftview.hidden = NO;
}

-(void)getInitData
{
    _giftLogic = [GiftLogic new];
    [_giftLogic getGiftListHookData:^(NSArray *giftList) {
        _giftList = giftList;
        _giftview = [[GiftView alloc]initWithShareViewToView:self.view AndGift:_giftList];
        _giftview.delegate = self;
        _giftview.hidden = YES;
        [self.view addSubview:_giftview];
        //        _giftview.hidden = YES;
    }];
}

#pragma mark - 礼物选择发送代理
-(void)giftSendClickWithInfo:(GiftModel *)model AndNumber:(NSInteger)number
{
    if(number == 0)
    {
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"需要选择发送礼物数量")];
        return;
    }
    __weak __typeof(self)weakSelf = self;
    self.giftLogic.touid = self.uid;
    [self.giftLogic sendGiftWith:model AndNumber:number Hook:^(BOOL sendSuccess, NSString *error, TIMMessage *message) {
        
        if(sendSuccess)
        {
            
        }
        else
        {
            NSLog(ASLocalizedString(@"发送失败，原因%@"),error);
        }
    }];
    
    NSLog(ASLocalizedString(@"选择发送的礼物是%@"),model.name);
}


-(void)getData
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"personal_api" A:@"get_user_page_info"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.uid forKey:@"id"];
    
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        _usermodel = [UserPageInfoModel modelWithJSON:responseObject];
        [self setContent];
    } failure:^(NSString *error) {
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
}

-(void)setContent
{
    [self.headerImage setImageURL:[cyurl safeUrl:_usermodel.avatar]];
    self.nickname.text = _usermodel.user_nickname;
}

//挂断电话
-(void)handleRefuseButtonEvent:(UIButton *)button
{
    NSString *tip = [NSString stringWithFormat:ASLocalizedString(@"确定要挂断视频吗")];
    QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:tip preferredStyle:QMUIAlertControllerStyleAlert];
    [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {

    }]];
    
    [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"确定")style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
//        [_timer invalidate];
//        _timer = nil;
//        [self leaveChannel];
        [self closeVideo];
        
    }]];
    [alert showWithAnimated:YES];
    
//    [HUDHelper alert:ASLocalizedString(@"确定要挂断视频吗")cancel:ASLocalizedString(@"取消")action:^{
//
//    }];
}

-(void)closeVideo
{
    [_timer invalidate];
    _timer = nil;
    [self leaveChannel];

}
//翻转摄像头
-(void)handlcameraEvent:(UIButton *)button
{
    [self doSwitchCameraPressed];
}

//关闭麦克风
-(void)handlemicrophonEvent:(UIButton *)button
{
    button.selected = !button.selected;
    [self doMutePressed];
}

-(void)setLayot
{
    [_topBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@28);
        make.left.equalTo(@15);
        make.width.greaterThanOrEqualTo(@100);
        make.right.equalTo(_nickname).offset(5);
        make.height.equalTo(@44);
    }];
    //头像
    [_headerImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.and.height.equalTo(@40);
        make.top.and.left.equalTo(@2);
    }];
    
    ViewRadius(_headerImage, 20);
    ViewRadius(_topBg, 44/2.0f);
    
    
    //昵称
    [_nickname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerImage.mas_right).offset(5);
        make.top.equalTo(_headerImage).offset(5);
    }];
    
    [_refuseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-10);
        make.left.equalTo(self.view).offset(10);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    
    [_microphoneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-10);
        make.right.equalTo(_cameraButton.mas_left).offset(-5);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    
    [_cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-10);
        make.right.equalTo(self.view).offset(-10);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    
    [_giftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-10);
        
        make.right.equalTo(_microphoneButton.mas_left).offset(-10);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    
    //    [_MaskButton mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.equalTo(self.view);
    //    }];
}


-(void)dealloc{
    [self stopService];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopService];
    
}

-(void)stopService
{
    NSLog(ASLocalizedString(@"移除了所有的通知"));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)startService
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callEnd:) name:KOnCallEnd object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRciverGiftMessage:) name:KOnGiftMessage object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRciverVideoProhibition:) name:KVideoProhibition object:nil];
    
    self.timer = [NSTimer timerWithTimeInterval:BuckleSecond target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _is_need_coin = 0;//标识没有加载
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"is_need_charging"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:SafeStr(self.uid) forKey:@"to_user_id"];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        _video_deduction = [responseObject valueForKey:@"video_deduction"];
        _roomTip.text = [NSString stringWithFormat:ASLocalizedString(@"每分钟通话扣除%@%@"),_video_deduction,KCOIN_NAME];
        
        if([[responseObject valueForKey:@"is_need_charging"] intValue] == 1)
        {
            _is_need_coin = 1;
        }
        else
        {
            _roomTip.text = ASLocalizedString(@"女性免费");
            _is_need_coin = 2;
        }
        [self timerAction];
        
        
    } failure:^(NSString *error) {
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
}

//强制挂断视频
- (void)onRciverVideoProhibition:(NSNotification *)notification{
    NSString *data = [notification.userInfo valueForKey:@"data"];
    
    [self closeVideo];
//    [self handleRefuseButtonEvent:nil];
    [HUDHelper alert:data action:^{
        
    }];
}


//收到礼物
- (void)onRciverGiftMessage:(NSNotification *)notification{
    UnifiedMessage *data = [notification.userInfo valueForKey:@"data"];
    LiveGiftListModel *giftModel = [[LiveGiftListModel alloc] init];
    
    giftModel.rewardMsg = data.from_msg;
    giftModel.goldCount = [NSString stringWithFormat:@"%ld",(long)data.to_ticket];
    giftModel.type = @"0";
    giftModel.picUrl = [safeurl(data.prop_icon) absoluteString];
    
    LiveUserModel *userModel = [[LiveUserModel alloc] init];
    
    userModel.name = @"fifth";
    
    if(_usermodel != nil)
    {
        userModel.name = _usermodel.user_nickname;
        userModel.iconUrl = [safeurl(_usermodel.avatar) absoluteString];
    }
    else
    {
        userModel.name = @"";
    }
    LiveGiftShowModel * model = [LiveGiftShowModel giftModel:giftModel userModel:userModel];
    
    //尝试计算数量
    model.toNumber = data.to_ticket/[data.to_diamonds integerValue];
    if(model.toNumber == 0)
    {
        model.toNumber = 1;
    }
    model.interval = 0.15;
    [self.customGiftShow animatedWithGiftModel:model];
}


- (void)callEnd:(NSNotification *)notification{
    NSLog(@"%@",notification.userInfo);
    [self closeVideo];
//    [self handleRefuseButtonEvent:self.refuseButton];
    NSLog(ASLocalizedString(@"---接收到通知（通话结束）---"));
    
}

-(void)timerAction
{
    self.second++;
    _callCount = [_video_deduction integerValue] * self.second;
    NSLog(ASLocalizedString(@"扣费调试%@====%d"),curUser.id,self.isCall);
    
    if(_is_need_coin == 1)
    {
        [self doCharging];
    }
    else
    {
        
    }
    
    if(!self.isCall)
    {
        return;
    }
    
}


-(void)doCharging
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"video_call_time_charging"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        //        _callCount = [_video_deduction integerValue] * self.second;
        NSLog(ASLocalizedString(@"成功"));
    } failure:^(NSString *error) {
        _showRecharge = YES;
//        [self handleRefuseButtonEvent:self.refuseButton];
        [MBProgressHUD showTopTipMessage:error];
//        [HUDHelper alert:error action:^{
//        }];
        [self closeVideo];
    } hasCache:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


/*
 礼物视图支持很多配置属性，开发者按需选择。
 */
- (LiveGiftShowCustom *)customGiftShow{
    if (!_customGiftShow) {
        _customGiftShow = [LiveGiftShowCustom addToView:self.view];
        _customGiftShow.addMode = LiveGiftAddModeAdd;
        [_customGiftShow setMaxGiftCount:3];
        [_customGiftShow setShowMode:LiveGiftShowModeFromTopToBottom];
        [_customGiftShow setAppearModel:LiveGiftAppearModeLeft];
        [_customGiftShow setHiddenModel:LiveGiftHiddenModeNone];
        [_customGiftShow enableInterfaceDebug:YES];
        _customGiftShow.delegate = self;
        _customGiftShow.backgroundColor = RGB(33, 33, 33);
    }
    return _customGiftShow;
}

@end
